import NProgress from 'nprogress'
import { createRouter, createWebHashHistory, type RouteRecordRaw } from 'vue-router'
import { sysUserApi } from '~/api'
import { sleepUtil } from '~/composables'
import { getToken, setToken, toLogin } from '~/composables/auth'
import 'nprogress/nprogress.css'

const isDev = import.meta.env.DEV

function DashboardComponent() {
  switch (__PAGE_DIR__) {
    case 'aaaaa':
      return import('~/views/aaaaa/aaaaa.vue')
    case 'bbbbb':
      return import('~/views/bbbbb/bbbbb.vue')
    case 'ccccc':
      return import('~/views/ccccc/ccccc.vue')
    case 'ddddd':
      return import('~/views/ddddd/ddddd.vue')
    case 'eeeee':
      return import('~/views/eeeee/eeeee.vue')
    default:
      return import('~/views/404/404.vue')
  }
}

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'EnergyDashboard',
    component: DashboardComponent,
  },
  {
    path: '/reload',
    name: 'Reload',
    component: () => import('~/views/reload/reload.vue'),
  },
  {
    path: '/404',
    name: '404',
    component: () => import('~/views/404/404.vue'),
  },
  { path: '/:pathMatch(.*)*', redirect: '/404' },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

const whiteList = [
  /^\/404$/,
  /^\/test$/i,
  /^\/reload$/i,
]

const ENERGY_SCREEN_DASHBOARD_PATH = '/energy-dashboard'

async function canIEnterEnergyScreenDashboard(path: string = ENERGY_SCREEN_DASHBOARD_PATH) {
  // 如果接口非200则认为没有权限
  try {
    await sysUserApi.hasMenu(path)
    return true
  }
  catch (e) {
    return false
  }
}

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  if (whiteList.some(v => v.test(to.path))) {
    next()
    return
  }
  if (isDev && to.query.token) {
    setToken(to.query.token as string)
    next({ path: to.path, replace: true })
    return
  }
  if (!getToken() || !await canIEnterEnergyScreenDashboard()) {
    console.error('您没有权限访问能耗生产看板页面')
    await sleepUtil.sleep(1000)
    next()
    toLogin()
    return
  }

  next()
})

router.afterEach(() => {
  NProgress.done()
})

export { router }
